﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data.SqlClient;

namespace ChatService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class GetChanelMessageService : IGetChanelMessages
    {

        public IEnumerable<string> GetChanels()
        {
            ChatEntities entities = new ChatEntities();
         
            IEnumerable<String> chanels = entities.Chanels.Select(c => c.Name);
            return chanels;
        }



        public IEnumerable<MessageDTO> GetMessages(string numberOfMessages, string chanelName)
        {
            int numberAsInt = int.Parse(numberOfMessages);
            ChatEntities entities = new ChatEntities();
      
            IEnumerable<MessageDTO> messages = entities.Chanels.First(c => c.Name == chanelName).Messages.OrderByDescending
                (m => m.TimeSend).Take(numberAsInt).Select(m => new MessageDTO() { MessageText = m.Text, MessageTime = m.TimeSend });
            foreach (var item in messages)
            {
                var i = item.MessageTime;
                var t = item.MessageText;
                Console.WriteLine();
            }
            return messages;
          
        }

  


        public void CreateChanel(string chanelName)
        {
        ChatEntities entities = new ChatEntities();
           
            Chanel chanel = entities.Chanels.FirstOrDefault(c => c.Name == chanelName);
            if (chanel == null)
            {
                chanel = new Chanel();
                chanel.Name = chanelName;
                entities.Chanels.AddObject(chanel);
            }
            else
            {
                IEnumerable<Message> Messages = entities.Chanels.First(c => c.Name == chanelName).Messages;
                foreach (var item in Messages)
                {
                    entities.Messages.DeleteObject(item);
                }
            }
            entities.SaveChanges();
            
        }


        public void PostMessage(Post newPost)
        {
            ChatEntities entities = new ChatEntities();
           
            Chanel chanel = entities.Chanels.First(c => c.Name == newPost.Chanel);
            Message newMessage = new Message();
            newMessage.Text = newPost.Message;
            newMessage.TimeSend = DateTime.Now;
            chanel.Messages.Add(newMessage);
            entities.SaveChanges();
            
        }
    }
}
